import { Component, Vue } from 'vue-property-decorator';

@Component
export default class ChatStreamHandler extends Vue {
    private buffer = '';
    private controller: AbortController | null = null;
    private pendingEvent: string | null = null; // 新增：用于跟踪未完成的event

    async fetchStream(prompt: string) {
        this.controller = new AbortController();

        const formData = new FormData();
        formData.append('robot_key', 'xFJsTsySbU');
        formData.append('openid', 'MFDobGgkKZiFlGu5Y');
        formData.append('question', prompt);
        formData.append('dialogue_id', '1'); // 数字会被自动转换为字符串
        try {
            const response = await fetch('/api/chat/request', {
                method: 'POST',
                body: formData,
                signal: this.controller.signal
            });

            await this.processStream(response);
        } catch (err) {
            if (err.name !== 'AbortError') {
                this.$emit('stream-error', err);
            }
        }
    }

    private async processStream(response: Response) {
        const reader = response.body?.getReader();
        const decoder = new TextDecoder();

        if (!reader) return;

        try {
            let isReading = true;
            while (isReading) {
                const { done, value } = await reader.read();
                if (done) {
                    isReading = false;
                    this.processRemainingBuffer();
                    break;
                }
                this.buffer += decoder.decode(value, { stream: true });
                this.parseBuffer();
            }
        } catch (err) {
            console.error('Stream reading error:', err);
        }
    }

    private parseBuffer() {
        const lines = this.buffer.split('\n');
        this.buffer = '';

        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();

            if (!line) continue;

            if (line.startsWith('event:')) {
                const eventType = line.substring(6).trim();

                // 检查是否有对应的data行
                if (i + 1 < lines.length && lines[i + 1].startsWith('data:')) {
                    const data = lines[++i].substring(5).trim();
                    this.handleEvent(eventType, data);
                } else {
                    // 保存未完成的event到buffer
                    this.buffer += line + '\n';
                    this.pendingEvent = eventType;
                }
            } else if (this.pendingEvent && line.startsWith('data:')) {
                const data = line.substring(5).trim();
                this.handleEvent(this.pendingEvent, data);
                this.pendingEvent = null;
            } else {
                // 保存未处理的行到buffer
                this.buffer += line + '\n';
            }
        }
    }

    private processRemainingBuffer() {
        if (this.buffer.trim().length > 0) {
            this.parseBuffer();
        }
    }

    private handleEvent(eventType: string, data: string) {
        console.log(eventType);
        console.log(data)
        try {
            switch (eventType) {
                case 'sending':{
                    this.$emit('stream-data', data);
                    break;
                }
                case 'ai_message':{
                    const parsedData = JSON.parse(data);
                    if (parsedData.content) {
                        // 处理可能包含<think>标签的内容
                        const content = parsedData.content
                            .replace(/<think>[\s\S]*?<\/think>/g, '') // 移除思考过程
                            .trim();
                        this.$emit('stream-data', content);
                    }
                    break;
                }
                case 'c_message':{
                    const messageData = JSON.parse(data);
                    this.$emit('message-received', messageData);
                    break;
                }
                case 'ping':
                case 'recall_time':
                    // 处理其他事件类型...
                    break;

                default:
                    console.warn('Unhandled event type:', eventType);
                    break;
            }
        } catch (err) {
            console.error('Error handling event:', err);
        }
    }

    abortStream() {
        this.controller?.abort();
        this.buffer = '';
        this.pendingEvent = null;
    }
}